<template>
	<view class="login" :class="{show:show}">
		<view class="mask" @tap="closeLogin"></view>
		<view class="container">
			<view class="close-box" @tap="closeLogin">
				<image class="close-img" src="/static/close.png" />
			</view>
			<view class="p-name">
				前端交流学习中心欢迎你
			</view>

			<u-form :model="form" ref="form" :rules="rules">
				<u-form-item label="电 话" prop="phone" label-width="80" required>
					<u-input v-model="form.phone" placeholder='输入11位手机号码' />
				</u-form-item>
				<u-form-item v-if="loginType==='code'" label="验证码" prop="code" required label-width="80">
					<u-input placeholder="请输入4位验证码" v-model="form.code" type="text"></u-input>
					<u-button slot="right" type="success" @click="getCode">获取验证码</u-button>
				</u-form-item>
				<u-form-item v-if="loginType==='phone'" label="密 码" label-width="80" required prop="password">
					<u-input v-model="form.password" type="password" placeholder='限4-20个字符' />
				</u-form-item>
				<view class="btns">
					<u-button type="primary" class="ubtn" @tap="submit">提交</u-button>
					<u-button class="ubtn" @tap="cancel">取消</u-button>
				</view>
			</u-form>

			<view class="switch">
				<text>验证码登录</text>
				<u-switch v-model="switchValue" @change="switchChange"></u-switch>
				<text>密码登录</text>
			</view>

			<view class="serve-info">点击登录/注册前端论坛，即表示已阅读并同意</view>
			<view class="serve-text">
				<view @tap="gotoWeb('https://uniapp.dcloud.io/component/mp-weixin-plugin')">《隐私政策》</view>
				<view @tap="gotoWeb('https://developers.weixin.qq.com/miniprogram/dev/framework/')">《用户协议》</view>
				<view @tap="gotoUrl('/subpages/register/register')">《用户注册》</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getLoginCode,
		userLogin,
		getUserMsg,
		findUser
	} from "@/common/api.js"
	import {
		mapState,
		mapActions
	} from "vuex"


	export default {
		name: "login",
		data() {
			return {
				// 控制组件显示
				show: false,
				// 表单用户输入数据
				form: {
					phone: '',
					code: '',
					password: ''
				},
				// 登陆方式 code 验证码，phone 电话
				loginType: 'code',
				switchValue: false,
				// 表单相关规则校验
				rules: {
					// 手机验证码登陆、手机验证码注册 使用
					phone: [{
						validator: (rule, value, callback) => {
							// 自带判断 电话号码合法性方法 uView 自带 moblie emial 校验
							return this.$u.test.mobile(value)
						},
						message: '必填 * 手机号码输入不正确',
						trigger: ['change', 'blur'],
					}],
					// 验证码验证
					code: [{
						validator: (rule, value, callback) => {
							// 名字长度为 2-10 位
							return value === '8888'
						},
						message: '必填 * 验证码长度为4位，并且固定值为 8888',
						// 触发器可以同时用blur和change
						trigger: ['change', 'blur'],
					}],
					// 密码验证
					password: [{
						validator: (rule, value, callback) => {
							// 名字长度为 4-20 位
							return (value.length >= 4 && value.length <= 20)
						},
						message: '必填  * 请输入 4-20 位密码',
						trigger: ['change', 'blur'],
					}]
				}
			};
		},
		computed: {
			...mapState(['loginState', 'userInfo'])
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			...mapActions(['userLoginAction', 'userLogoutAction']),
			// 取消表单输入
			cancel() {
				this.form = {
					phone: '',
					code: '',
					password: ''
				}
			},
			// 关闭弹窗
			closeLogin() {
				this.show = false
				this.cancel()
			},
			// 打开登陆弹窗
			openLogin() {
				this.show = true
			},
			// 跳转到 H5 页面
			gotoWeb(url) {
				uni.navigateTo({
					url: '/pages/webview/webview?url=' + encodeURI(url)
				});
			},
			gotoUrl(url) {
				uni.navigateTo({
					url
				})
			},
			// 切换登录方式
			switchChange(e) {
				if (e) {
					this.loginType = "phone"
				} else {
					this.loginType = "code"
				}
			},
			// 获取验证码
			async getCode() {
				let pcode = await getLoginCode({
					phone: this.form.phone
				})
				if (!!pcode.message && pcode.message[0] === "获取成功") {
					uni.showModal({
						title: '验证码获取成功',
						content: '8888'
					})
				} else {
					uni.showModal({
						title: '验证码获取失败',
						content: "当前手机号码未注册"
					})
				}
			},
			// 提交表单登陆
			submit() {
				this.$refs.form.validate().then(async valid => {
					switch (this.loginType) {
						case "phone":
							let pres = await userLogin({
								login: this.form.phone,
								password: this.form.password,
							})
							if (pres.token_type === "Bearer") {
								// 登陆成功
								this.loginAfter(pres.access_token)
							} else {
								uni.showModal({
									title: '登陆失败',
									content: pres.message
								})
							}
							break;
						case "code":
							let cres = await userLogin({
								login: this.form.phone,
								verifiable_code: '8888'
							})
							if (cres.token_type === "Bearer") {
								// 登陆成功
								this.loginAfter(cres.access_token)
							} else {
								uni.showModal({
									title: '登陆失败',
									content: cres.message
								})
							}
							break;
					}
				})
			},
			// 登陆成功后执行的逻辑
			async loginAfter(token) {
				console.log("登录成功");
				this.show = false
				uni.setStorageSync('token', token)

				let res = await findUser({
					name: this.form.phone
				})
				let user = await getUserMsg()
				let loginInfo = {
					name: res.name,
					phone: res.phone,
					avatar: res.avatar,
					bio: res.bio,
					liked: user.user.liked,
					commented: user.user.commented
				}
				this.userLoginAction(loginInfo)
				uni.$emit("indexUserLogin")
				uni.$emit("UserLoginMe")
			}
		}
	}
</script>

<style lang="scss" scoped>
	.login {
		position: fixed;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		display: flex;
		align-items: flex-end;
		opacity: 0;
		transition: opacity 300, z-index 0 300;
		pointer-events: none;
		z-index: 999;

		&.show {
			z-index: 9999;
			opacity: 1;
			pointer-events: auto;
		}

		.mask {
			position: fixed;
			width: 100%;
			height: 100%;
			background-color: rgba($color: #000000, $alpha: 0.3);
		}

		.container {
			z-index: 999;
			display: flex;
			flex-direction: column;
			width: 710upx;
			padding: 40upx 20upx;
			background-color: #f1f1f1;
			border-radius: 20upx;
			align-items: center;
			position: relative;

			.p-name {
				margin: 20upx 0upx;
				font-size: 36upx;
				font-weight: normal;
			}

			.close-box {
				position: absolute;
				right: 12upx;
				top: 20upx;
				width: 56.56upx;
				height: 56.56upx;
				padding: 10upx;

				.close-img {
					width: 50%;
					height: 50%;
				}
			}
		}

		.header {
			display: flex;
			flex-direction: column;
			align-items: center;
			font-size: 28upx;

			.logo-wrap {
				width: 144upx;
				height: 144upx;
				overflow: hidden;
				border-radius: 20upx;
			}

			.logo {
				width: 100%;
				height: 100%;
			}
		}

		.info {
			color: #333;
		}

		.submit-btn {
			width: 642upx;
			height: 88upx;
			margin-top: 60upx;
			margin-bottom: 60upx;
			border-radius: 44upx;
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: center;
			color: #fff;
			background-color: #0046f5;
			font-size: 36upx;

			.wechat-img {
				width: 44upx;
				height: 34upx;
				margin: 0 18upx;
			}
		}

		.phone-login {
			color: #0046f5;
			font-size: 28upx;
			margin-top: 40upx;
			border: none;
			background-color: #f1f1f1;
		}

		.cancel-btn {
			width: 100%;
			margin-top: 60upx;
			color: #333;
			background-color: #f1f1f1;
		}

		.serve-info {
			font-size: 22upx;
			margin-top: 20upx;
		}

		.serve-text {
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: center;
			font-size: 22upx;
			color: #6079b8;
			margin-top: 10upx;
		}
	}

	button::after {
		border: none;
	}

	.btns {
		margin-top: 20upx;
		text-align: center;

		.ubtn {
			width: 200upx;
		}
	}

	.type {
		margin-top: 80upx;
	}

	.switch {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: center;
		font-size: 26upx;
		color: #888;
		margin-top: 20upx;

		text {
			margin: 0 20upx;
		}
	}
</style>
